# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class PhoneSpider(CrawlSpider):
    name = 'phone'
    allowed_domains = ['zol.com.cn','zol-img.com.cn','detail.zol.com.cn']
    start_urls = ['http://detail.zol.com.cn/notebook_index/subcate16_list_1.html']

    rules = (
        Rule(LinkExtractor(allow=r'detail.zol.com.cn/notebook/index\d+.shtml'), callback='parse_item', follow=True),
        # Rule(LinkExtractor(allow=r'detail.zol.com.cn/notebook/index1211145.shtml'), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        i = {}
        i['name']=response.xpath('//h1[@class="product-model__name"]/text()').extract_first()
        i['alias']=response.xpath('//h2[@class="product-model__alias"]/text()').extract_first()
        i['subtitle']=response.xpath('//div[@class="product-model__subtitle"]/text()').extract_first()
        i['main_img']=response.xpath('//div[@class="big-pic"]/a/img/@src').extract_first()
        i['price_cankao']=response.xpath('//b[@class="price-type"]/text()').extract_first()
        i['price_jd']=response.xpath('//li[@class="b2c-jd"]/a[2]/text()').extract_first()
        i['price_tmall']=response.xpath('//li[@class="b2c-tmall"]/a[2]/text()').extract_first()
        i['imgs']=response.xpath('//ul[@class="_j_eva_slider"]/li/a/img/@src').extract()
        i['score']=response.xpath('//div[@class="total-score"]/strong/text()').extract_first()
        i['score_pepo']=response.xpath('//div[@class="total-score"]/div[2]/span/text()').extract_first()
        score_detail=response.xpath('//div[@class="circle-value"]/text()').extract()
        score_detail_titile=response.xpath('//div[@class="circle-text"]/text()').extract()
        i.update(dict(zip(score_detail_titile,score_detail)))
        detail_path=response.xpath('//div[@class="section-header-link"]/a[@class="_j_MP_more more"]/@href').extract_first()
        detail_path='http://detail.zol.com.cn%s'%detail_path
        print(i)
        yield scrapy.Request(
            detail_path,callback=self.parse_detail_param,meta={'item':i}
        )

        # yield i

    def parse_detail_param(self,response):
        print('-----------------------------')
        item=response.meta['item']
        param_list=response.xpath('//table/tr[position()>1]')
        for p in param_list:
            title=p.xpath('./th/span/text()').extract_first()
            if title:
                item[title]=p.xpath('./td/span/text()').extract_first()
        print(item)
        yield item
